import { Button, Form, FormItem, Uploader } from "@nutui/nutui-react-taro";
import { useImmer } from "use-immer";
import { beforeXhrUpload } from "@/utils/upload";
import { api } from "@/utils/api-instance";
import { useAppDispatch } from "@/hook";
import { getUserInfo } from "@/features/user/userSlice";
import Taro from "@tarojs/taro";
import { DeliverInput } from "@/apis/__generated/model/static";
import { Dictionaries } from "@/apis/__generated/model/enums/DictConstants";
import "./deliver-register.scss";

export default function DeliverRegister() {
  const dispatch = useAppDispatch();
  const [from, setForm] = useImmer<DeliverInput>({
    idCardBack: "",
    idCardFront: "",
    status: "WAIT",
  });
  Taro.useLoad(async () => {
    const res = await api.deliverForFrontController.query({
      body: { pageNum: 1, pageSize: 100, query: {} },
    });
    if (res.content.length > 0) {
      setForm(res.content[0]);
    }
  });
  const handleSubmit = async () => {
    await api.deliverForFrontController.save({ body: from });
    console.log(from);
    dispatch(getUserInfo());
    Taro.showToast({ title: "提交成功", icon: "success" });
  };
  return (
    <div className="deliver-register">
      <Form>
        <FormItem label="身份证正面" name="front">
          <Uploader
            key={1}
            beforeXhrUpload={beforeXhrUpload}
            maxCount={1}
            onSuccess={(params) => {
              setForm((draft) => {
                draft.idCardFront = params.responseText;
              });
            }}
          ></Uploader>
        </FormItem>
        <FormItem label="身份证反面" name="back">
          <Uploader
            key={2}
            beforeXhrUpload={beforeXhrUpload}
            maxCount={1}
            onSuccess={(params) => {
              setForm((draft) => {
                draft.idCardBack = params.responseText;
              });
            }}
          ></Uploader>
        </FormItem>
        {from.id ? (
          <FormItem label="状态" name="status">
            <div>{Dictionaries.ApproveStatus[from.status].keyName}</div>
          </FormItem>
        ) : (
          ""
        )}
        <Button
          className="submit-btn"
          block
          type="primary"
          onClick={handleSubmit}
        >
          提交
        </Button>
      </Form>
    </div>
  );
}
